export function Node(v) {
    return {
        v,
        next: null,
        first: function* (n) {
            yield this.v
            console.log('first', n, this.v, this.next);
            if (this.next && n > 1) {
                yield* this.next.first(n - 1)
            }
        },
        sorted_add: function (v) {
            if (this.v <= v && this.next === null) {
                n = Node(v);
                this.next = n;
                return;
            }
            if (this.v <= v && v <= this.next.v) {
                n = Node(v);
                n.next = this.next;
                this.next = n;
                return;
            }
        }
    }
}

export function LinkedList() {
    return {
        head: null,
        next: null,
        add: function (v) {
            if (!this.head) {
                this.head = Node(v);
                return this.head;
            }
            let cur = this.head;
            while (cur.next) {
                cur = cur.next;
            }
            cur.next = Node(v);
            return cur.next;
        },
        sorted_add: function () {
            if (this.head.v > v) {
                let n = Node(v);
                n.next = this.head;
                this.head = n;
                return;
            }
            if (this.head) {
                this.head.sorted_add(v)
            }
        },
        pophead: function () {
            v = this.head.v;
            this.head = this.head.next;
            return v;
        },
        print: function () {
            let cur = this.head;
            while (cur) {
                console.log(cur.v);
                cur = cur.next;
            }
        },
        first: function (n) {
            if (this.head) {
                return this.head.first(n);
            }
        },
        movehead: function () {
            this.head = this.head.next;
        }

    }
}